package cn.cxj.pay.controller;

import cn.cxj.basic.util.QuartzUtils;
import cn.cxj.order.domain.AdoptOrder;
import cn.cxj.order.domain.ProductOrder;
import cn.cxj.order.service.IAdoptOrderService;
import cn.cxj.order.service.IProductOrderService;
import cn.cxj.order.service.IProductService;
import cn.cxj.pay.domain.PayBill;
import cn.cxj.pay.service.IPayBillService;
import cn.cxj.quartz.service.IQuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAdoptOrderService adoptOrderService;

    @Autowired
    private IQuartzService quartzService;

    @Autowired
    private IProductOrderService productOrderService;

    /**
     * 支付宝支付请求成功以后异步回调
     */
    @RequestMapping("/notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){
        System.out.println("异步回调...");
        try {
            // 获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            /*boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type); //调用SDK验证签名
            */
            // 验签成功
            //if(signVerified) {
                // 商户订单号 --> orderSn
                String out_trade_no = request.getParameter("out_trade_no");
                // 支付宝交易号 --> unionPaySn
                String trade_no = request.getParameter("trade_no");
                // 交易状态
                String trade_status = request.getParameter("trade_status");
                if(trade_status.equals("TRADE_FINISHED")){
                    // 程序走到这里说明订单完成
                }else if (trade_status.equals("TRADE_SUCCESS")){
                    // 程序走到这里说明支付成功
                    // 基于商户订单号查询支付单表,修改状态为已支付
                    PayBill payBill = payBillService.queryByOrderSn(out_trade_no);
                    payBill.setState(1);
                    payBill.setUpdateTime(new Date());
                    payBill.setUnionPaySn(trade_no);
                    payBillService.update(payBill);
                    // 修改订单表信息
                    successBackUpdate(payBill);
                    // 取消定时器
                    quartzService.removeJob(out_trade_no);
                }

                return "success";

           // }else {//验证失败
           //     return "false";
           // }
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

    @RequestMapping("/returnUrl")
    public String returnUrl(){
        System.out.println("同步回调...");
        return "redirect:http://127.0.0.1/success.html";

    }


    /**
     * 成功以后根据支付方式查询并修改订单表数据
     *
     * @param payBill
     */
    private void successBackUpdate(PayBill payBill) {
        String orderType = payBill.getBusinessType();
        if (orderType == null) {
            return;
        }
        switch (orderType) {
            case "adopt_order" :
                // 领养订单
                Long businessKey = payBill.getBusinessKey();
                AdoptOrder adoptOrder = adoptOrderService.queryById(businessKey);
                // 状态设置为已支付
                adoptOrder.setState(1);
                adoptOrder.setPaySn(payBill.getUnionPaySn());
                adoptOrderService.update(adoptOrder);
                break;
            case "product_order" :
                // 服务订单
                Long businessKey2 = payBill.getBusinessKey();
                ProductOrder productOrder = productOrderService.queryById(businessKey2);
                productOrder.setState(1);
                productOrder.setPaySn(payBill.getUnionPaySn());
                productOrderService.update(productOrder);
                break;
        }

    }
}
